const cloud = require('wx-server-sdk')
const utils = require('./utils')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

/**
 * 候选人管理云函数主入口
 */
exports.main = async (event, context) => {
  const { action } = event

  try {
    switch (action) {
      case 'create':
        return await createCandidate(event, context)
      case 'update':
        return await updateCandidate(event, context)
      case 'delete':
        return await deleteCandidate(event, context)
      case 'getDetail':
        return await getCandidateDetail(event, context)
      case 'getList':
        return await getCandidateList(event, context)
      case 'uploadImage':
        return await uploadImage(event, context)
      case 'uploadVideo':
        return await uploadVideo(event, context)
      case 'deleteFile':
        return await deleteFile(event, context)
      case 'vote':
        return await voteForCandidate(event, context)
      case 'createTestData':
        return await createTestData(event, context)
      case 'initDB':
        const dbInit = require('./db-init')
        return await dbInit.initDatabase()
      case 'cleanTestData':
        const testDataClean = require('./test-data')
        return await testDataClean.cleanTestData()
      default:
        return {
          success: false,
          message: '无效的操作类型'
        }
    }
  } catch (error) {
    console.error('候选人管理云函数错误:', error)
    return {
      success: false,
      message: '服务器错误',
      error: error.message
    }
  }
}

// 创建候选人
async function createCandidate(event, context) {
  const { candidateData } = event
  const { openid } = cloud.getWXContext()

  // 清理和验证数据
  const cleanData = utils.sanitizeCandidateData(candidateData)
  const validation = utils.validateCandidateData(cleanData)
  
  if (!validation.isValid) {
    return {
      success: false,
      message: validation.errors.join(', ')
    }
  }

  const now = new Date()
  
  try {
    // 创建候选人记录
    const candidateRecord = {
      ...cleanData,
      votes: 0, // 初始票数为0
      ranking: 0, // 初始排名为0
      sortWeight: utils.calculateSortWeight(0, now), // 排序权重
      createdBy: openid,
      createdAt: now,
      updatedAt: now,
      status: 'active' // active, inactive, deleted
    }

    const result = await db.collection('candidates').add({
      data: candidateRecord
    })

    if (result._id) {
      // 获取刚创建的候选人完整信息
      const candidate = await db.collection('candidates').doc(result._id).get()
      
      return {
        success: true,
        message: '候选人创建成功',
        data: {
          _id: result._id,
          ...candidate.data
        }
      }
    } else {
      throw new Error('创建候选人失败')
    }
  } catch (error) {
    console.error('创建候选人错误:', error)
    return {
      success: false,
      message: '创建候选人失败',
      error: error.message
    }
  }
}

// 更新候选人
async function updateCandidate(event, context) {
  const { candidateId, candidateData } = event
  const { openid } = cloud.getWXContext()

  if (!candidateId) {
    return {
      success: false,
      message: '候选人ID不能为空'
    }
  }

  // 清理数据
  const cleanData = utils.sanitizeCandidateData(candidateData)
  
  // 验证图片数量限制
  if (cleanData.images && !utils.validateImageCount(cleanData.images.length)) {
    return {
      success: false,
      message: `图片数量不能超过${utils.MAX_IMAGE_COUNT}张`
    }
  }

  try {
    // 检查候选人是否存在
    const candidateResult = await db.collection('candidates').doc(candidateId).get()
    if (!candidateResult.data) {
      return {
        success: false,
        message: '候选人不存在'
      }
    }

    // 构建更新数据
    const updateData = {
      updatedAt: new Date()
    }

    // 只更新提供的字段
    if (cleanData.name !== undefined) updateData.name = cleanData.name
    if (cleanData.description !== undefined) updateData.description = cleanData.description
    if (cleanData.images !== undefined) updateData.images = cleanData.images
    if (cleanData.videoUrl !== undefined) updateData.videoUrl = cleanData.videoUrl
    if (candidateData.videoPoster !== undefined) updateData.videoPoster = candidateData.videoPoster
    if (cleanData.audioUrl !== undefined) updateData.audioUrl = cleanData.audioUrl
    if (cleanData.extraInfo !== undefined) updateData.extraInfo = cleanData.extraInfo
    if (candidateData.status !== undefined) updateData.status = candidateData.status

    // 如果票数发生变化，重新计算排序权重
    if (candidateData.votes !== undefined) {
      updateData.votes = candidateData.votes
      updateData.sortWeight = utils.calculateSortWeight(candidateData.votes, candidateResult.data.createdAt)
    }

    const result = await db.collection('candidates').doc(candidateId).update({
      data: updateData
    })

    if (result.stats.updated > 0) {
      // 获取更新后的候选人信息
      const updatedCandidate = await db.collection('candidates').doc(candidateId).get()
      
      return {
        success: true,
        message: '候选人更新成功',
        data: updatedCandidate.data
      }
    } else {
      return {
        success: false,
        message: '候选人更新失败'
      }
    }
  } catch (error) {
    console.error('更新候选人错误:', error)
    return {
      success: false,
      message: '更新候选人失败',
      error: error.message
    }
  }
}

// 删除候选人
async function deleteCandidate(event, context) {
  const { candidateId, forceDelete = false } = event
  const { openid } = cloud.getWXContext()

  if (!candidateId) {
    return {
      success: false,
      message: '候选人ID不能为空'
    }
  }

  try {
    // 检查候选人是否存在
    const candidateResult = await db.collection('candidates').doc(candidateId).get()
    if (!candidateResult.data) {
      return {
        success: false,
        message: '候选人不存在'
      }
    }

    const candidate = candidateResult.data

    let result
    if (forceDelete) {
      // 物理删除
      result = await db.collection('candidates').doc(candidateId).remove()
    } else {
      // 软删除：将状态改为deleted
      result = await db.collection('candidates').doc(candidateId).update({
        data: {
          status: 'deleted',
          deletedAt: new Date(),
          deletedBy: openid,
          updatedAt: new Date()
        }
      })
    }

    if ((forceDelete && result.stats.removed > 0) || (!forceDelete && result.stats.updated > 0)) {
      // 删除相关的云存储文件
      try {
        const filesToDelete = []
        
        // 添加图片文件
        if (candidate.images && candidate.images.length > 0) {
          filesToDelete.push(...candidate.images)
        }

        // 添加视频文件
        if (candidate.videoUrl) {
          filesToDelete.push(candidate.videoUrl)
        }

        // 添加音频文件
        if (candidate.audioUrl) {
          filesToDelete.push(candidate.audioUrl)
        }

        if (filesToDelete.length > 0) {
          await utils.batchDeleteFiles(filesToDelete)
        }
      } catch (fileError) {
        console.error('删除文件失败:', fileError)
        // 文件删除失败不影响数据库删除
      }

      return {
        success: true,
        message: '候选人删除成功'
      }
    } else {
      return {
        success: false,
        message: '候选人删除失败'
      }
    }
  } catch (error) {
    console.error('删除候选人错误:', error)
    return {
      success: false,
      message: '删除候选人失败',
      error: error.message
    }
  }
}

// 获取候选人详情
async function getCandidateDetail(event, context) {
  const { candidateId } = event

  if (!candidateId) {
    return {
      success: false,
      message: '候选人ID不能为空'
    }
  }

  try {
    const result = await db.collection('candidates')
      .doc(candidateId)
      .get()

    if (result.data && result.data.status !== 'deleted') {
      return {
        success: true,
        data: result.data
      }
    } else {
      return {
        success: false,
        message: '候选人不存在'
      }
    }
  } catch (error) {
    console.error('获取候选人详情错误:', error)
    return {
      success: false,
      message: '获取候选人详情失败',
      error: error.message
    }
  }
}

// 获取候选人列表
async function getCandidateList(event, context) {
  const { 
    activityId, 
    status = 'active', 
    page = 1, 
    pageSize = 20,
    sortBy = 'votes' // votes, created, name
  } = event

  try {
    let query = db.collection('candidates')

    // 根据活动ID筛选
    if (activityId) {
      query = query.where({
        activityId: activityId,
        status: status
      })
    } else {
      query = query.where({
        status: status
      })
    }

    // 分页
    const skip = (page - 1) * pageSize
    
    // 获取总数
    const countResult = await query.count()
    const total = countResult.total

    // 根据排序方式排序
    let orderBy
    switch (sortBy) {
      case 'votes':
        orderBy = [['sortWeight', 'desc']] // 使用预计算的排序权重
        break
      case 'created':
        orderBy = [['createdAt', 'desc']]
        break
      case 'name':
        orderBy = [['name', 'asc']]
        break
      default:
        orderBy = [['votes', 'desc'], ['createdAt', 'asc']]
    }

    // 构建查询
    let listQuery = query
    for (const [field, direction] of orderBy) {
      listQuery = listQuery.orderBy(field, direction)
    }

    // 获取列表数据
    const listResult = await listQuery
      .skip(skip)
      .limit(pageSize)
      .get()

    return {
      success: true,
      data: {
        list: listResult.data,
        total: total,
        page: page,
        pageSize: pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    }
  } catch (error) {
    console.error('获取候选人列表错误:', error)
    return {
      success: false,
      message: '获取候选人列表失败',
      error: error.message
    }
  }
}

// 上传图片
async function uploadImage(event, context) {
  const { candidateId, imageIndex, fileBuffer, fileName } = event

  if (!candidateId || imageIndex === undefined || !fileName) {
    return {
      success: false,
      message: '候选人ID、图片索引和文件名不能为空'
    }
  }

  // 验证文件格式
  if (!utils.validateImageFormat(fileName)) {
    return {
      success: false,
      message: `仅支持以下图片格式: ${utils.SUPPORTED_IMAGE_FORMATS.join(', ')}`
    }
  }

  try {
    const extension = utils.getFileExtension(fileName)
    const cloudPath = utils.generateImagePath(candidateId, imageIndex, extension)
    
    const uploadResult = await cloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: fileBuffer
    })

    if (uploadResult.fileID) {
      return {
        success: true,
        data: {
          fileID: uploadResult.fileID,
          cloudPath: cloudPath
        }
      }
    } else {
      return {
        success: false,
        message: '图片上传失败'
      }
    }
  } catch (error) {
    console.error('上传图片错误:', error)
    return {
      success: false,
      message: '上传图片失败',
      error: error.message
    }
  }
}

// 上传视频
async function uploadVideo(event, context) {
  const { candidateId, fileBuffer, fileName, fileSize } = event

  if (!candidateId || !fileName) {
    return {
      success: false,
      message: '候选人ID和文件名不能为空'
    }
  }

  // 验证文件格式
  if (!utils.validateVideoFormat(fileName)) {
    return {
      success: false,
      message: `仅支持以下视频格式: ${utils.SUPPORTED_VIDEO_FORMATS.join(', ')}`
    }
  }

  // 验证文件大小
  if (fileSize && !utils.validateVideoSize(fileSize)) {
    return {
      success: false,
      message: `视频文件大小不能超过${utils.MAX_VIDEO_SIZE / (1024 * 1024)}MB`
    }
  }

  try {
    const extension = utils.getFileExtension(fileName)
    const cloudPath = utils.generateVideoPath(candidateId, extension)
    
    const uploadResult = await cloud.uploadFile({
      cloudPath: cloudPath,
      fileContent: fileBuffer
    })

    if (uploadResult.fileID) {
      return {
        success: true,
        data: {
          fileID: uploadResult.fileID,
          cloudPath: cloudPath
        }
      }
    } else {
      return {
        success: false,
        message: '视频上传失败'
      }
    }
  } catch (error) {
    console.error('上传视频错误:', error)
    return {
      success: false,
      message: '上传视频失败',
      error: error.message
    }
  }
}

// 删除文件
async function deleteFile(event, context) {
  const { fileList } = event

  if (!fileList || !Array.isArray(fileList)) {
    return {
      success: false,
      message: '文件列表不能为空'
    }
  }

  try {
    const result = await utils.batchDeleteFiles(fileList)
    return {
      success: result.success,
      data: result
    }
  } catch (error) {
    console.error('删除文件错误:', error)
    return {
      success: false,
      message: '删除文件失败',
      error: error.message
    }
  }
}

// 投票功能
async function voteForCandidate(event, context) {
  const { candidateId, userId } = event

  if (!candidateId || !userId) {
    return {
      success: false,
      message: '候选人ID和用户ID不能为空'
    }
  }

  try {
    // 检查候选人是否存在
    const candidateResult = await db.collection('candidates').doc(candidateId).get()
    if (!candidateResult.data) {
      return {
        success: false,
        message: '候选人不存在'
      }
    }

    // 更新候选人票数
    const updateData = {
      votes: candidateResult.data.votes + 1,
      updatedAt: new Date()
    }

    const result = await db.collection('candidates').doc(candidateId).update({
      data: updateData
    })

    if (result.stats.updated > 0) {
      // 获取更新后的候选人信息
      const updatedCandidate = await db.collection('candidates').doc(candidateId).get()
      
      return {
        success: true,
        message: '候选人投票成功',
        data: updatedCandidate.data
      }
    } else {
      return {
        success: false,
        message: '候选人投票失败'
      }
    }
  } catch (error) {
    console.error('投票错误:', error)
    return {
      success: false,
      message: '投票失败',
      error: error.message
    }
  }
}

// 创建测试数据
async function createTestData(event, context) {
  const testData = require('./test-data')
  return await testData.createTestData()
} 